<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>聊天室</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0" name="viewport" />
    <meta content="no-cache,must-revalidate" http-equiv="Cache-Control" />
    <meta content="telephone=no, address=no" name="format-detection" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta content="no-cache" http-equiv="pragma" />
    <meta content="0" http-equiv="expires" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
    <link rel="stylesheet" type="text/css" href="../../public/static/api/css/public.css" />
    <link rel="stylesheet" type="text/css" href="../../public/static/api/css/chat.css?1=4   " />
    <link href="../../public/static/api/css/swiper-3.4.1.min.css" rel="stylesheet" />

    <script type="text/javascript" src="../../public/static/api/js/jquery-2.0.2.min.js"></script>
    <script type="text/javascript" src="../../public/static/api/js/size.js"></script>
    <script src="../../public/static/api/js/layer.js"></script>
    <script src="../../public//static/api/js/jquery.form.js"></script>
    <script src="../../public/static/api/js/swiper-3.4.1.jquery.min.js"></script>
    <!--<script src='static/js/jquery.min.js'></script>
	<script src='static/js/strophe.min.js'></script>-->
    <script src="../../public/static/api/js/strophe.min.js"></script>
    <script src='../../public/static/api/js/strophe.register.js'></script>
    <script src="../../public/static/api/js/imhander.js"></script>
    <style>
        .layui-m-layer2 .layui-m-layercont i{background:rgba(0,0,0,0.5)}
    </style>
</head>
<body>
<form name="form1" method="post" action="" id="form1" enctype="multipart/form-data">
    <div>
        <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTUyMzc2NjE4MWRkcJMRluerAj2vq42hcGjTvBsEQ/E3YuCNBgY+2uJJMcs=" />
    </div>

    <div>

        <input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="CA58D1D6" />
        <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEdAAJA1Ed/SD6bBBUVBlyRZk26wohoMm1zOOMHLkwCXpMPtpZ9mO2K/Eh2VqdXu06qOeKkg6EkAsD9/0PmPbAtIt/B" />
    </div>
    <section class="main_box">
        <div class="clear"></div>

        <div class="record_box" style="position:absolute;">
            <div class="tit">
                <span class="k-name tospace">{$qzInfo['ClubName'] ? $qzInfo['ClubName'] : ''}</span>
                <span class="t-room">房号：{$data[0]['TableID']}</span>
                <span class="r-time">
                    <div style="font-size:14px;display: flex;justify-content: space-between;margin-left:0.3rem;margin-right:3rem;">
                        <span style="font-size:16px;">{$data[0]['ServiceName']}</span>
                        <span style="padding-top:3px;">{$data[0]['EndTime']}</span>
                    </div>
                </span>
                {if($qzInfo)}
                <span style="display:block;height:20px;width:55px;border-radius:8px;font-size: 12px;position:absolute;right:17px; top:10px;z-index: 999;background-color: #FF6262;">群主名片</span>
                <span style="position:absolute;right:20px; top:20px;">
                    <img id="iface_{$qzInfo['uid']}" onclick=cardImg("{$qzInfo['uid']}") style="width:50px;height:50px;border-radius: 5px;" src="{$qzInfo['FaceUrl']|baseDeCode}">
                    <span id="iname_{$qzInfo['uid']}" style="display: none;">{$qzInfo['NickName']}(群主)</span>
                </span>
                {/if}
                <div class="clear"></div>
            </div>
            <div class="list">
                <ul>
                    {volist name="data" id="val" empty="$empty"}
                        <li onclick=cardImg("{$val.Uid}");>
                            {if($uid == $val.Uid)}<span class='master'></span>{/if}
                            {if($val.WinUid == $val.Uid)}<span class='winner'>大赢家</span>{/if}
                            <span class="head">
                                <img id="iface_{$val.Uid}" src="{$val.FaceUrl|baseDeCode}"/><!--../images/timg.jpg-->
                            </span>
                            <span id="iname_{$val.Uid}" class="name tospace">{$val.NickName}</span>
                            <span class="name">ID:{$val.Uid}</span>
                            <span class="score {$val.TotalScore > 0 ? 'score_w' : ''}">{$val.TotalScore}</span>
                        </li>
                    {/volist}
                    <div class="clear"></div>
                </ul>
            </div>
            <div class="tip">

                <span style="color:#000000;font-weight: 600">(点头像有惊喜)</span><br/>

                结果仅用于比赛参考
            </div>
        </div>
        <div class="clear"></div>
    {if($is_sense)}
        <div class="chat_box">
            <div class="record_line"></div>
            <ul id="chatlist" style="background-color: #F1F2F7;">
                {volist name="chatData" id="val" empty="$empty"}
                <li class="{$uid==$val.uid ? 'current' : ''}">
                    <div class="head">
                        <img src="{$val.FaceUrl|baseDeCode}">
                    </div>
                    <div class="name">
                        {$val.NickName}{$val.uid == $qzInfo['uid'] ? '(群主)' : ''}
                    </div>
                    <div class="chat">
                        <div class="box"></div>
                        {$val.message}
                    </div>
                    <div class="clear">
                    </div>
                </li>
                {/volist}
            </ul>
        </div>
        <div class="emotiction">
            <dl id="bqList">
                {volist name="bqData" id="val"}
                <dt id="dt_{$val.id}">
                <span onclick="sendBq('{$val.id}')">
                    {$val.message}
                </span>
                <span class='btn-close' data-val='' ><img onclick="delBq('{$val.id}')" src='/public/static/api/images/close.png'/></span>
                </dt>
                {/volist}
            </dl>
            <input id="btnupload" type="button" class="btnupload" value="+"/>
        </div>
        <div class="send">
            <input id="txtmsg" style="font-size: 16px;" type="text" class="intxt" maxlength="500" />
            <input id="btnemo" type="button" class="btnupload" value=""/>
            <input id="btnsend" type="button" class="btnsend" value=""/>
            <input type="file" name="fileupImg" id="fileupImg" onchange="fun_uploadimg(this.value)"  style="display:none;" />
        </div>
    {else/}
        <div style="margin-top:90%;">
            <div class="tip">您没在该牌局里...</div>
        </div>
    {/if}
        <div class="clear"></div>

    </section>


    <input type="file" name="fileupload_card" id="fileupload_card" onchange="upload_card(this.value)"  style="display:none;" />
    <section id="info-box" style="display: none;">
        <div class="info-box">
            <div class="close" onclick="closeLay()"></div>
            <div class="info">
                    <span class="head">
                        <img id="spnface" src="/public/static/api/images/touxiang.jpg"/>
                    </span>
                <span id="spnname" class="name">
                        名称：Picky
                    </span>
                <span id="spnuid" class="name">
                        ID：000138
                    </span>
                <div class="clear"></div>
            </div>
            <div class="card-img">
                <img id="spncard" src="/public/static/api/images/erweima.jpg" class="default"/>
            </div>
            <div class="card-upload">
                <input id="btnuploadcard" onclick="editMp()" type="button" class="btn" />
            </div>
        </div>
    </section>


</form>

<script type="text/javascript">

    $("input,select").blur(function(){
        setTimeout(function() {
            var scrollHeight = document.documentElement.scrollTop || document.body.scrollTop || 0;
            window.scrollTo(0, Math.max(scrollHeight - 1, 0));
        }, 10);
    })

    //上传名片
    function upload_card(str){
        str = str.toLowerCase();
        var strRegex = "(.jpg|.jpeg|.png)$"; //用于验证图片扩展名的正则表达式
        var re = new RegExp(strRegex);
        if (!re.test(str)) {

            layer.open({
                content: '图片格式有误!'
                , skin: 'msg'
                , time: 2 //2秒后自动关闭
            });
            return (false);
        }
        //开始提交
        // FormData对象，来发送二进制文件。
        var formdata = new FormData();
        // 将文件追加到 formdata对象中。
        formdata.append("img",$('#fileupload_card')[0].files[0]);
        formdata.append("uid","{$uid}");
        formdata.append("scoreId","{$scoreId}");
        layer.open({ type: 2, shade: false,content: '上传中...',style:'color:red;' });  // load 加载
        $.ajax({
            type: "POST",
            url: "{:url('uploadCard')}",
            data:formdata,
            async: false,
            cache:false,
            contentType: false,
            processData: false,
            dataType: "json",
            success: function(e){
                layer.closeAll();
                layer.open({
                    content: '上传成功'
                    , skin: 'msg'
                    , time: 2 //2秒后自动关闭
                });
            },
            error: function(jqXHR){
                alert("发生错误：" + jqXHR.status);
            },
        });
    }

    //关闭名片弹框
    function closeLay(){
        layer.closeAll();
    }

    //编辑名片
    function editMp(){
        $("#fileupload_card").click();
    }

    var _infobox = $("#info-box").html();

    if ($(".record_box .list li").length <= 4) {
        $(".record_line").css("height", "7.5rem");
        $(".record_box").css("height", "7.5rem");
        $(".chat_box ul").css("height", "calc(100% - 9.1rem)");
    } else {
        $(".record_line").css("height", "11rem");
        $(".record_box").css("height", "11rem");
        $(".chat_box ul").css("height", "calc(100% - 12.5rem)");
    }

    //点击头像显示名片弹出框
    function cardImg(id){
        /*if("{$is_sense}" == 0){

            return;
        }*/
        if (id == "{$uid}") {
            $("#spncard").width("80%");
            $(".card-upload").css('display','block')
        }else{
            $("#spncard").width("100%");
            $(".card-upload").css('display','none')
        }

        var data = {
            uid:id,
            scoreId:"{$scoreId}",
        }
        $.post("{:url('getPhotocard')}",data,function(res){
            var list = eval('(' + res + ')');
            console.log(list);
            $("#spnface").attr("src", list.FaceUrl + "?rnd=" + Math.random());
            $("#spnname").text("名称："+list.NickName);
            $("#spnuid").text("ID：" + list.uid);
            var photo_card = list.photo_card ? list.photo_card : "/public/static/api/images/nullimg.jpg";
            $("#spncard").attr("src", photo_card);

            _infobox = $("#info-box").html();

            layer.open({
                type: 1
                , content: _infobox
                , anim: 'up'
                , style: 'position:fixed; left:1rem; top:10%; width:8rem; height:12rem;border-radius:4px;background:#F1F2F7; border: none; -webkit-animation-duration: .5s; animation-duration: .5s;'
            });

        });



    }

    //删除表情
    function delBq(id){
        $("#dt_"+id).remove();
        //修改图片状态为文字
        var data = {
            uid:"{$uid}",
            mesId:id,
            scoreId:"{$scoreId}",
        }
        $.post("{:url('delBq')}",data,function(res){
            console.log(res)
        });
    }

    //点击发送表情
    function sendBq(id){
        var data = {
            uid:"{$uid}",
            mesId:id,
            scoreId:"{$scoreId}",
        }
        $.post("{:url('sendBq')}",data,function(res){
            console.log(res)
            $(".emotiction").hide();
        });
    }

    window.onload = function(){
        chat_bottom();
    }
    $(function () {
        /**
         * 与GatewayWorker建立websocket连接，域名和端口改为你实际的域名端口，
         * 其中端口为Gateway端口，即start_gateway.php指定的端口。
         * start_gateway.php 中需要指定websocket协议，像这样
         * $gateway = new Gateway(websocket://0.0.0.0:7272);
         */
        //ws = new WebSocket("ws://127.0.0.1:7272");
        ws = new WebSocket("ws://{:config('host')}:7272");
        // 服务端主动推送消息时会触发这里的onmessage
        ws.onmessage = function(e){
            // json数据转换成js对象
            var data = eval("("+e.data+")");
            var type = data.type || '';
            switch(type){
                // Events.php中返回的init类型的消息，将client_id发给后台进行uid绑定
                case 'init':
                    // 利用jquery发起ajax请求，将client_id发给后端进行uid绑定
                    $.post("{:url('bind')}", {client_id: data.client_id,scoreId:"{$scoreId}"}, function(data){

                    }, 'json');
                    break;
                //有新消息时
                case 'new_msg':
                    //头像
                    var face = $("#iface_"+data.msg.uid).attr('src');
                    //昵称
                    var name = $("#iname_"+data.msg.uid).text();
                    var msgline = "<li>";
                    if(data.msg.uid == "{$uid}"){
                        msgline = "<li class='current'>";
                    }
                    msgline += "<div class='head'><img src='"+face+"'/></div>";
                    msgline += "<div class='name'>"+name+"</div>";
                    msgline += "<div class='chat'>";
                    msgline += "<div class='box'></div>"+data.msg.message+"";
                    msgline += "</div>";
                    msgline += "<div class='clear'></div>";
                    msgline += "</li>";
                    $('#chatlist').append(msgline);
                    $('#txtmsg').val('');
                    chat_bottom();
                //心跳消息
                default :
                    console.log(e.data);
            }
        };

    });
    //点击发送
    $('#btnsend').click(function () {
        var msg = $('#txtmsg').val();
        if (msg.trim().length == 0) {
            layer.open({
                content: '请输入消息内容.'
                , skin: 'msg'
                , time: 2 //2秒后自动关闭
            });
            return;
        }
        // 发送消息
        sendMsg(msg.trim());
    });
    //POST发送信息到后台
    function sendMsg(msg){
        var data = {
            uid:"{$uid}",
            scoreId:"{$scoreId}",
            message:msg,
        }
        $.post("{:url('sendMsg')}",data,function(res){
            console.log(res)
        });
    }

    // 回到聊天底部
    function chat_bottom() {
        var chat = document.getElementById("chatlist");
        chat.scrollTop = chat.scrollHeight;
    }

    //点击图片加号
    $("#btnemo").click(function () {
        if ($(".emotiction").css("display") == "block") {
            $(".emotiction").hide();
        } else {
            $(".emotiction").show();
        }
    });

    //点击+号 选择图片
    $("#btnupload").click(function () {
        $("#fileupImg").click();
    });

    //发送图片
    function fun_uploadimg(str) {
        str = str.toLowerCase();
        var strRegex = "(.jpg|.jpeg|.png)$"; //用于验证图片扩展名的正则表达式
        var re = new RegExp(strRegex);
        if (!re.test(str)) {

            layer.open({
                content: '图片格式有误!'
                , skin: 'msg'
                , time: 2 //2秒后自动关闭
            });
            return (false);
        }
        //开始提交
        // FormData对象，来发送二进制文件。
        var formdata = new FormData();
        // 将文件追加到 formdata对象中。
        formdata.append("img",$('#fileupImg')[0].files[0]);
        formdata.append("uid","{$uid}");
        formdata.append("scoreId","{$scoreId}");
        layer.open({ type: 2, shade: false,content: '发送中...',style:'color:red;' });  // load 加载
        $.ajax({
            type: "POST",
            url: "{:url('sendPic')}",
            data:formdata,
            async: false,
            cache:false,
            contentType: false,
            processData: false,
            dataType: "json",
            success: function(e){
                var data = eval("("+e+")");
                var msg = data.msg;
                console.log(msg);
                layer.closeAll();
                //删除列表最后一个表情
                var length = $("#bqList").children("dt").length-1;
                if(length == 3){
                    $("#bqList").children("dt").get(length).remove();
                }
                //将新发送的图片追加到第一个
                var html = "<dt id='dt_"+msg.id+"'>";
                html+="<span onclick=sendBq("+msg.id+")>"+msg.message;
                html+="</span>";
                html+="<span class='btn-close' data-val='' ><img onclick=delBq("+msg.id+") src='/public/static/api/images/close.png'/></span>";
                html+="</dt>";
                $("#bqList").prepend(html);

                $(".emotiction").hide();
            },
            error: function(jqXHR){
                alert("发生错误：" + jqXHR.status);
                $(".emotiction").hide();
            },
        });
    }


</script>
</body>
</html>
